package com.example.ping;

import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class PingService extends Service {
    private static final String TARGET_IP = "192.168.62.41";
    private static final String LOG_FILE_NAME = "ping_results.txt";
    private static final int MAX_LINES = 86400;

    @Override
    public void onCreate() {
        super.onCreate();
        startPing(4000);
    }

    private void startPing(int timeout) {
        new Thread(() -> {
            try {
                File externalDir = Environment.getExternalStorageDirectory();
                File logFile = new File(externalDir, LOG_FILE_NAME);
                if (logFile.length()>100*1024*1024) {//如果大于100mb，则清楚后重新建
                    logFile.delete();
                    logFile.createNewFile();
                }
                FileWriter writer = new FileWriter(logFile, true);
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

                while (true) {
                    long startTime = System.currentTimeMillis();
                    boolean isReachable = isPortReachable(TARGET_IP,19008,timeout);
                    long endTime = System.currentTimeMillis();
                    long duration = endTime - startTime;
                    String pingTime = dateFormat.format(new Date());
                    String result = "Ping Time: " + pingTime + ", IP: " + TARGET_IP + ", Duration: " + duration + "ms, Status: " + (isReachable ? "Success" : "Failed") + "\n";
                    System.out.println(result);
                    writer.write(result);
                    writer.flush();
                    Thread.sleep(timeout);
                }
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

    private boolean isPortReachable(String ip, int port, int timeout) {
        try (Socket socket = new Socket()) {
            socket.connect(new InetSocketAddress(ip, port), timeout);
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    private void manageLogFile(File logFile, String newRecord) throws IOException {
        List<String> lines = new ArrayList<>();
        // 读取文件所有行
        try (BufferedReader reader = new BufferedReader(new FileReader(logFile))) {
            String line;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
        }

        // 添加新记录
        lines.add(newRecord);

        // 如果超过最大行数，移除最旧的记录
        if (lines.size() > MAX_LINES) {
            lines.remove(0);
        }

        // 将更新后的记录写回文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(logFile))) {
            for (String line : lines) {
                writer.write(line);
                writer.newLine();
            }
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}